import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import glob
import threading
import win32com.client


def toggle_input_state():
    """根据选择的调整选项启用或禁用输入框"""
    if resize_option.get() == "比例:固定":
        width_entry.config(state="normal")
        height_entry.config(state="normal")
        scale_factor_entry.config(state="disabled")
    else:
        width_entry.config(state="disabled")
        height_entry.config(state="disabled")
        scale_factor_entry.config(state="normal")


def resize_images(
    input_path,
    output_path,
    new_width,
    new_height,
    scale_factor,
    file_format,
    update_progress,
):
    # 创建Photoshop应用的实例
    psApp = win32com.client.Dispatch("Photoshop.Application")
    psApp.Visible = True

    # 获取所有图片文件
    image_files = glob.glob(input_path + "/*.bmp") + glob.glob(input_path + "/*.jpg")
    total_images = len(image_files)

    # 遍历图片文件
    for index, filepath in enumerate(image_files, start=1):
        # 更新进度信息
        update_progress(f"处理中: 图片 {index} / {total_images}")

        # 获取原始文件名
        original_file_name = os.path.basename(filepath)
        # 新文件的完整路径
        new_file_path = os.path.join(output_path, original_file_name)

        # 打开图片文件
        doc = psApp.Open(filepath)

        # 调整图像大小
        # 根据选择的调整选项调整图像大小
        if resize_option.get() == "比例:固定":
            doc.ResizeImage(Width=new_width, Height=new_height)
        else:
            if scale_factor:
                current_width, current_height = doc.width, doc.height
                new_width = current_width * scale_factor
                new_height = current_height * scale_factor
                doc.ResizeImage(Width=new_width, Height=new_height)

        # 保存更改为BMP或JPEG格式
        if filepath.lower().endswith(".bmp"):
            options = win32com.client.Dispatch("Photoshop.BMPSaveOptions")
            options.Depth = 24
        else:
            options = win32com.client.Dispatch("Photoshop.JPEGSaveOptions")
            options.Quality = 12

        # 保存更改为BMP或JPEG格式
        if file_format == "BMP":
            options = win32com.client.Dispatch("Photoshop.BMPSaveOptions")
            options.Depth = 24
            # 更改文件扩展名为.bmp
            new_file_path = os.path.splitext(new_file_path)[0] + ".bmp"
        else:
            options = win32com.client.Dispatch("Photoshop.JPEGSaveOptions")
            options.Quality = 12
            # 更改文件扩展名为.jpg
            new_file_path = os.path.splitext(new_file_path)[0] + ".jpg"

        doc.SaveAs(new_file_path, options)
        # 关闭文档
        doc.Close()
    # 更新进度信息
    update_progress("转换完成！所有图片处理完毕。")


def start_resizing():
    input_path = input_path_entry.get()
    output_path = output_path_entry.get()
    file_format = format_combobox.get()

    if not os.path.exists(input_path) or not os.path.exists(output_path):
        messagebox.showwarning("错误", "请检查文件夹路径是否正确！")
        return

    if resize_option.get() == "比例:固定":
        try:
            new_width = int(width_entry.get())
            new_height = int(height_entry.get())
        except ValueError:
            messagebox.showwarning("错误", "宽度和高度必须是数字！")
            return
        scale_factor = None
    else:
        new_width = new_height = None
        try:
            scale_factor = float(scale_factor_entry.get())
            if not 0.001 <= scale_factor <= 10.000:
                raise ValueError
        except ValueError:
            messagebox.showwarning("错误", "缩放比例必须在0.001到10.000之间！")
            return

    threading.Thread(
        target=resize_images,
        args=(
            input_path,
            output_path,
            new_width,
            new_height,
            scale_factor,
            file_format,
            update_progress_label,
        ),
    ).start()


def update_progress_label(message):
    progress_label.config(text=message)
    root.update_idletasks()


def select_input_path():
    path = filedialog.askdirectory()
    input_path_entry.delete(0, tk.END)
    input_path_entry.insert(0, path)


def select_output_path():
    path = filedialog.askdirectory()
    output_path_entry.delete(0, tk.END)
    output_path_entry.insert(0, path)

# 创建主窗口
root = tk.Tk()
root.title("(图片像素调整工具)-杨赞接")
# 主布局Frame
main_frame = tk.Frame(root)
main_frame.grid(padx=10, pady=10)

# 输入文件夹路径
tk.Label(main_frame, text="输入文件夹:").grid(row=0, column=0, sticky="w")
input_path_entry = tk.Entry(main_frame, width=50)
input_path_entry.grid(row=0, column=1)
tk.Button(main_frame, text="选择", command=select_input_path).grid(row=0, column=2)

# 输出文件夹路径
tk.Label(main_frame, text="输出文件夹:").grid(row=1, column=0, sticky="w")
output_path_entry = tk.Entry(main_frame, width=50)
output_path_entry.grid(row=1, column=1)
tk.Button(main_frame, text="选择", command=select_output_path).grid(row=1, column=2)

# 分辨率宽度输入
tk.Label(main_frame, text="宽度:").grid(row=2, column=0, sticky="w")
width_entry = tk.Entry(main_frame, width=10)
width_entry.grid(row=2, column=1, sticky="w")

# 分辨率高度输入
tk.Label(main_frame, text="高度:").grid(row=3, column=0, sticky="w")
height_entry = tk.Entry(main_frame, width=10)
height_entry.grid(row=3, column=1, sticky="w")

# 文件格式选择
tk.Label(main_frame, text="转换后文件格式:").grid(row=4, column=0, sticky="w")
format_combobox = ttk.Combobox(main_frame, values=["JPG", "BMP"], width=48)
format_combobox.grid(row=4, column=1, sticky="w")
format_combobox.current(0)  # 默认选择第一个选项

# 缩放比例输入
tk.Label(main_frame, text="缩放比例 (0.001 - 10.000):").grid(row=5, column=0, sticky="w")
scale_factor_entry = tk.Entry(main_frame, width=10)
scale_factor_entry.grid(row=5, column=1, sticky="w")

# 调整选项 - 固定宽高或按比例缩放
resize_option = tk.StringVar(value="比例:固定")
tk.Radiobutton(
    main_frame,
    text="固定宽高",
    variable=resize_option,
    value="比例:固定",
    command=toggle_input_state,
).grid(row=6, column=0, sticky="w")
tk.Radiobutton(
    main_frame,
    text="按比例缩放",
    variable=resize_option,
    value="比例:缩放",
    command=toggle_input_state,
).grid(row=6, column=1, sticky="w")

# 开始按钮和进度标签
tk.Button(main_frame, text="开始转换", command=start_resizing).grid(
    row=7, column=1, sticky="e"
)
progress_label = tk.Label(main_frame, text="")
progress_label.grid(row=8, column=0, columnspan=3)

# 启动初始状态
toggle_input_state()

# 运行主循环
root.mainloop()
